[cfe-dev] Rewriter::InsertText
Douglas Gregor
dgregor at apple.com
Thu Aug 5 03:17:29 PDT 2010
On Aug 5, 2010, at 12:04 PM, Сергей Филиппов wrote:
> Hi,
> I'm facing strange bug with Rewriter::InsertText.
> Here is the code:
>
> void RewritingPass::Initialize(ASTContext &context)
> {
> this->context = &context;
> SourceLocation L;
> mainFileId = context.getSourceManager().getMainFileID();
> rewriter = new Rewriter(context.getSourceManager(), context.getLangOptions());
> const llvm::StringRef preamble(getPreamble());
> if (preamble.size() > 0)
> rewriter->InsertText(context.getSourceManager().getLocForStartOfFile(mainFileId), preamble, true);
> }
StringRef is a reference to a string that exists somewhere in memory; it doesn't copy the contents of the string. In this case, getPreamble() returns a temporary, and the preamble StringRef refers to that temporary's storage. When the temporary is destroyed, the storage goes away... and you get strange behavior. Capture the result of getPreamble() in a local string, then pass that along to InsertText.
It's generally not a good idea to have a StringRef variable.
- Doug
More information about the cfe-dev
mailing list