Translate C/C++ patern: return a pointer

Nicholas Wilson iamthewilsonator at hotmail.com
Thu May 24 08:58:02 UTC 2018


On Thursday, 24 May 2018 at 08:16:30 UTC, biocyberman wrote:
> Some C and C++ projects I am working on use pointers and 
> references extensively: to pass as function arguments, and to 
> return from a function. For function argument I would use 
> `ref`, but for return types, I can't use `ref` and can't return 
> a pointer. What should be the proper way to handle this? Do I 
> have to change function signature (i.e. return type) For 
> example, the following function:
>
> ```
> //C++ version, from:
> https://github.com/bioslaD/fastp/blob/orig/src/read.cpp#L69
>
> Read* Read::reverseComplement(){
> 	Sequence seq = ~mSeq;
> 	string qual;
> 	qual.assign(mQuality.rbegin(), mQuality.rend());
> 	string strand = (mStrand=="+") ? "-" : "+";
> 	return new Read(mName, seq, strand, qual);
> }
>
> // D version:
> Read reverseComplement(){
>     Sequence seq = ~mSeq;
>     dchar[] qual = cast(dchar[])mQuality.dup;
>     reverse(qual);
>     string strand = (mStrand=="+") ? "-" : "+";
>     Read newRead = new Read(mName, seq, strand, 
> cast(string)qual);
>     // return &newRead does not work: returning `& newRead` 
> escapes a reference to local variable newRead
>     return newRead;
>
>   }
>
>
> ```
> Let's not focus on the function body, I don't know how to 
> handle the return type in cases like this for the D version.

it looks like Read is a D class? in which case it already returns 
by reference.
If you make Read a struct then all you need do is change the 
function signature from
Read reverseComplement()
to
Read* reverseComplement()

about the function body
use mQuality.dup.representation.reverse;

>     dchar[] qual = cast(dchar[])mQuality.dup;
>     reverse(qual);
>     mQuality = cast(string)qual;

does not do what you want it to do.


More information about the Digitalmars-d-learn mailing list