Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: xfer string example from CTR51-CPP -> STR52-CPP

...

Code Block
bgColor#ccccff
langcpp
#include <algorithm>
#include <deque>
#include <iterator>
 
void f(const double *items, std::size_t count) {
  std::deque<double> d;
  std::transform(items, items + count, std::inserter(d, d.begin()),
                 [](double d) { return d + 41.0; });
}

Noncompliant Code Example

In this noncompliant code example, data is invalidated after the call to replace(), and so its use in g() is undefined behavior:

Code Block
bgColor#ffcccc
langcpp
#include <iostream>
#include <string>
 
extern void g(const char *);
 
void f(std::string &exampleString) {
  const char *data = exampleString.data();
  // ...
  exampleString.replace(0, 2, "bb");
  // ...
  g(data);

}

Compliant Solution

In this compliant solution, the pointer to exampleString's internal buffer is not generated until after the modifications from replace() have completed:

Code Block
bgColor#ccccff
langcpp
#include <iostream>
#include <string>

extern void g(const char *);

void f(std::string &exampleString) {
  // ...
  exampleString.replace(0, 2, "bb");
  // ...
  g(exampleString.data());
}

Risk Assessment

Using invalid references, pointers, or iterators to reference elements of a container results in undefined behavior.

...