如果我通过:: operator new(nbytes)分配了一些内存,后来我在这个池中通过"new(where)what"构建了一些相应类型的objs(但是小于nbytes),有没有办法检查未初始化的内存在哪里开始?
例
struct T{};
short noOfObj = 10;
T* p = static_cast<T*>(::operator new(sizeof(T) * noOfObj));
for (short i = 0; i < (noOfObj - 2); ++i)//here I'm constructing two less obj than available mem
{
new (p + i) T();
}
Run Code Online (Sandbox Code Playgroud)
我怎么能检查(不知道noOfObj已经减少了多少)p指向的未初始化内存开始了?(觉得我再次搞砸了语法,但我担心我现在能做的最好)
我希望能够做到这一点:
X<int> type_0;
X<int> type_1;
Run Code Online (Sandbox Code Playgroud)
我希望type_0和type_1是两种不同的类型.我该怎么做?
可能重复:
使用模板获取数组的大小和结束地址有人可以解释这个模板代码,它给我一个数组的大小?(第一个答案包括获取值作为编译时间常量)
如何使用元编程获得数组的大小?多维也将受到赞赏.所以例如,如果我将一个类型传递给这个结构(如何调用它,让我们说get_dim)我会得到:
get_dim<int>::value; //0
get_dim<int[1]>::value //1
get_dim<int[2][3]>::value //2,3
Run Code Online (Sandbox Code Playgroud) 为什么这个输出为零?我怀疑有些编译器在工作,但为什么呢?
signed int sint_ = numeric_limits<signed int>::min() << '\n';
cout << "signed int: " << sint_ << '\n';
Run Code Online (Sandbox Code Playgroud) unsigned int i = 0x02081;
cout << std::hex << i;
Run Code Online (Sandbox Code Playgroud)
使用VS2010编译时显示2081,但我认为它应显示0x02081.我是对的,如果是的话,如何解决这个问题?
char* cc = "Something string like";
char* ccn = new char[2];
ccn[0] = 'a';
ccn[1] = '\0';
cout << cc;
Run Code Online (Sandbox Code Playgroud)
第二个指针,为了防止内存泄漏,应该是delete[]'但是如何检测指针是否实际指向新的内存(如第一行中的那个)?第一个字符串在哪里创建?
我正在尝试学习C++的新功能,即移动构造函数和赋值X::operator=(X&&),我发现了一些有趣的例子, 但我唯一不理解但更不同意的是移动ctor和赋值运算符中的一行(在下面的代码中标记):
MemoryBlock(MemoryBlock&& other)
: _data(NULL)
, _length(0)
{
std::cout << "In MemoryBlock(MemoryBlock&&). length = "
<< other._length << ". Moving resource." << std::endl;
// Copy the data pointer and its length from the
// source object.
_data = other._data;
_length = other._length;
// Release the data pointer from the source object so that
// the destructor does not free the memory multiple times.
other._data = NULL;
other._length = 0;//WHY WOULD I EVEN BOTHER TO SET IT …Run Code Online (Sandbox Code Playgroud) 为什么执行此代码:
// DefaultAny.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <exception>
using std::cout;
template<class T>
struct NoReturnPolicy
{
static void calculate(T& result, const T& source)
{
result = source;
}
};
template<class T>
struct ReturnPolicy
{
static T& calculate(T& result, const T& source)
{
result = source;
return result;
}
};
template<class T>
struct ThrowPolicy
{
static void check(T* ptr)
{
cout << "ThrowPolicy";
struct Nullptr: public std::exception{};
if(!ptr)
{
throw Nullptr("Nullptr …Run Code Online (Sandbox Code Playgroud) 您是否知道任何现代语言,其中数组被标记为列/行而不是C++/Java/C#row/column中的数组?